package com.itheima.admin.contorller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.Orders;
import com.itheima.entity.OrdersDetails;
import com.itheima.entity.dto.OrdersDto;
import com.itheima.service.OrdersDetailsService;
import com.itheima.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : sky
 * @date : 2023/3/6 15:24
 * @modyified By :
 */
@RequestMapping("order")
@Api(tags = "订单控制器")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersDetailsService ordersDetailsService;
    /**
     * 订单分页查询
     *
     * @return
     **/
    @GetMapping("page")
    @ApiOperation("订单分页")
    public JsonResult getOrderByPage(String beginTime, String endTime, String number,
                                     Integer page, Integer pageSize){
        //构造条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getNumber,number);
        //=大于等于下单时间
        wrapper.ge(Orders::getOrderTime,beginTime );
        //小于等于结账时间
        wrapper.le(Orders::getCheckoutTime,endTime);
        //构造分页
        Page<Orders> pageinfo = new Page<>(page, pageSize);
        Page<Orders> ordersPage = ordersService.page(pageinfo, wrapper);
          return JsonResult.success(ordersPage);
    }
    /**
     * 订单修改
     *
     * @return
     */
@PutMapping
@ApiOperation("修改订单")
    public JsonResult updateOrders(@RequestBody OrdersDto ordersDto){
   //修改订单
    //1.1判断状态，"0",不能修改
   if (ordersDto.getStatus().equals("0")){
       throw new MyException(404, "不能修改订单");
   }
    //1.2.修改订单
    Orders orders = new Orders();
   //复制对象
    BeanUtil.copyProperties(ordersDto, orders);
    //修改订单
    ordersService.updateById(orders);
    // 删除原有的订单详情
    LambdaQueryWrapper<OrdersDetails> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(OrdersDetails::getOrdersId,ordersDto.getId());
    ordersDetailsService.remove(wrapper);
    //添加新的订单详情
    List<OrdersDetails> list = ordersDto.getOrdersDetails();
    //设置orderid
    List<OrdersDetails> details = list.stream().map(ordersDetails -> {
        ordersDetails.setOrdersId(ordersDto.getId());
        return ordersDetails;
    }).collect(Collectors.toList());
    //插入orderid
    ordersDetailsService.saveBatch(details);
    return JsonResult.success("添加成功！");
}
}
